package com.future.baselib.entity;

import android.text.TextUtils;

import com.future.baselib.utils.JLog;
import com.future.baselib.utils.LogUtils;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class BaseResponse {

    public int returnNo = -1;
    public String erroMessage;
    public String message;
    public String content;

    public void parseJson(String json, int code) {
        JLog.e("json", "json --- " + json);
        JLog.e("json", "code --- " + code);
        try {
            if (TextUtils.isEmpty(json)) {
                returnNo = code;
                if (returnNo == 500)
                    erroMessage = "服务器链接失败";
                else if (returnNo == 404)
                    erroMessage = "链接失效";
                else if (returnNo == 405)
                    erroMessage = "不支持的请求资源";
                else if (returnNo == 403)
                    erroMessage = "未授权";
                else if (returnNo == 503)
                    erroMessage = "服务器正在维护";
                else if (returnNo == 401)
                    erroMessage = "请重新登录";
                else if (returnNo == 110)
                    erroMessage = "账号已被禁用";
                return;
            }
            JSONObject object = new JSONObject(json);
            returnNo = object.optInt("code", -1);
            message = object.optString("msg");
            if (returnNo == 1) {
                if (object.optJSONObject("data") != null) {
                    content = object.optJSONObject("data").toString();
                    parseInfo(content);
                } else if (object.optJSONArray("data") != null) {
                    content = object.optJSONArray("data").toString();
                    parseInfo(content);
                } else {
                    content = object.optString("data");
                }
            } else {
                if (returnNo == 110) {
                    erroMessage = "账号被禁用";
                    message = "账号被禁用";
                } if (returnNo == 401) {
                    erroMessage = "请重新登录";
                    message = "请重新登录";
                }else if (code == 0) {
                    erroMessage = message;
                }
            }
        }
        catch (JSONException e) {
            LogUtils.e("BaseResponse", "json格式有误:" + e.getMessage());
            returnNo = 0;
            erroMessage = "数据格式错误";
        } catch (JsonSyntaxException e) {
            returnNo = 0;
            LogUtils.e("BaseResponse", "json格式有误:" + e.getMessage());
            erroMessage = "数据格式错误";
        }
    }

    public abstract void parseInfo(String content) throws JSONException;


}
